"use strict"

var Router = require('koa-router');
var config = require('../../config/config.js');
var debug = require('debug')('router_thread');
var dao = require('../../dao/thread.js');
var userDao = require('../../dao/user.js');
// var md5 = require('../../common/app_utils.js').md5;
var ferror = require('../../common/app_utils.js').formatError;
var fout = require('../../common/app_utils.js').formatOutput;
var errInfo = require('../../common/err_info.js');

debug('router:' + config.http.baseUrl + '/v1/thread');
var router = new Router({
	prefix: config.http.baseUrl + '/v1/thread'
});
module.exports = router.routes();
/**
add a thread
post /forum/v1/thread 
{
	title: 'bla',
	content: 'foobar'
}
*/
router.post('/', function*() {
	// debug('add thread');
	// check input TODO
	// check session
	var userId = this.session.userId;
	var result;
	if (!userId) {
		debug('no session', errInfo.E2100);
		this.body = ferror(errInfo.E2100);
	} else {
		var inParams = this.request.inParams;
		inParams.userId = userId;
		this.body = yield dao.create(inParams);
	}
});

router.get('/list', function*() {
	// deylay
	var inParams = this.request.inParams; // page:1,size:10
	var threads = yield dao.read(inParams);

	// if have userId, then get the userName
	if (threads.errCode !== 0) {
		return this.body = threads;
	}

	var phase2 = [];
	for (var item of threads.result) {
		var user = yield userDao.readById(item.userId);
		// TODO collect ids , and find one time
		// {_id:$in:[id1,id2,...]} 
		var r = item.toObject(); // item.name=xxx, not work
		r.userName = (user.errCode == 0) ? user.result.name : 'Eunknown';
		phase2.push(r);
	}
	threads.result = phase2;
	this.body = threads;
});